package com.example.android.debuggermenu;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Vector;

import com.example.android.debuggermenu.MessageList.MessageListAdapter;

import clientcore.GameState;
import clientcore.Message;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class InviteList extends ListActivity {
	private Vector<Message> inviteList = new Vector<Message>();
	private Context mContext = this;
	private String buddyName = null, buddyMessage = null;
	private String[] friends;
	private AlertDialog inviteAlert;
	private ArrayAdapter<Message> myAdapter;
	private int numOfChats=0, numOfInvites=0;
	private HashMap<String, Boolean> buds = new HashMap<String, Boolean>();
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//Bundle listBundle = getIntent().getExtras();
		//friends = listBundle.getStringArray("flist");
		Log.d("InviteList", "get the list");
		inviteList = GameState.getInviteList();
		Log.d("InviteList", "size: " + inviteList.size());
		new loadData().execute();
		
	}
	
	public void onListItemClick(ListView parent, View v, int position, long id) {
		Message item = (Message) parent.getItemAtPosition(position);
		buddyName = item.getSender();
		buddyMessage = item.getText();
		boolean alreadyFriend = false;
		/*
		for (int i = 0; i < friends.length; i++) {
			if (buddyName.equals(friends[i])) {
				alreadyFriend = true;
				break;
			}
		}
		*/
		AlertDialog.Builder inviteBuilder = new AlertDialog.Builder(mContext);
		
		if (alreadyFriend == false) {
			inviteBuilder.setMessage(buddyName + " wants to be your friend!\n" + buddyMessage)
			   .setCancelable(false)
			   .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
				   public void onClick(DialogInterface dialog, int id) {
					   inviteAlert.dismiss();
					   GameState.respondToInvite(buddyName, true);
					   Toast.makeText(mContext, "Invite Accepted!", Toast.LENGTH_LONG).show();
				   }
		       })
		       .setNegativeButton("No", new DialogInterface.OnClickListener() {
		    	   public void onClick(DialogInterface dialog, int id) {
		    		   inviteAlert.dismiss();
		    		   GameState.respondToInvite(buddyName, false);
		    	   }
		       });
		} else {
			inviteBuilder.setMessage(buddyName + " is already your friend!")
			   .setCancelable(false)
			   .setNeutralButton("Close", new DialogInterface.OnClickListener() {
				   public void onClick(DialogInterface dialog, int id) {
					   inviteAlert.dismiss();
					   GameState.respondToInvite(buddyName, false);
		           }
		       });
		}
		
		inviteAlert = inviteBuilder.show();
		GameState.removeInvite(position);
		inviteList = GameState.getInviteList();
		myAdapter.notifyDataSetChanged();
	}
	
	
	
class InviteListAdapter extends ArrayAdapter<Message> {
	private Vector<Message> invites;
    	
	public InviteListAdapter(Context context, int textViewResourceId, Vector<Message> items) {
    	super(context, textViewResourceId, items);
    	this.invites = items;
    }
    	
    public View getView(int position, View convertView, ViewGroup parent) {
    	View v = convertView;
    	if (v == null) {
    		LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    		v = vi.inflate(R.layout.invite_row, null);
    	}
    	Message chat = invites.get(position);
    	TextView name = (TextView) v.findViewById(R.id.invite_username);
    	TextView text = (TextView) v.findViewById(R.id.invite_message);
    	name.setText(chat.getSender());
    	text.setText(chat.getText());
    	return v;
    }
}
	
private class loadData extends AsyncTask<Void, Void, HashMap<String, Boolean>> {
	private ProgressDialog dialog;

	protected void onPreExecute() {
		Log.d("LoadBuddies", "begin onPreExecute");
		dialog = new ProgressDialog(mContext);
		dialog.setMessage("Loading Buddy List...");
		dialog.setCancelable(false); 
		dialog.show();
	}
	
	@Override
	protected HashMap<String, Boolean> doInBackground(Void... arg0) {
		Log.d("LoadBuddies", "begin doInBackground");
		
		Vector<Message> chatMessages = GameState.updatePrivateChats();
		Log.d("getChats", "connection made");
		for(Message m : chatMessages) {
	      	Log.d("CHATS", "SENDER: " + m.getSender() + " MESSAGE: " + m.getText());
	      	GameState.addMessage(m);
	    }
		numOfChats = chatMessages.size();
		chatMessages.clear();
		
		Vector<Message> inviteMessages = GameState.updateBuddyInvites();
		Log.d("LoadBuddies", "connection made for invites");
		for(Message m : inviteMessages) {
        	Log.d("BUDDY INVITES", "SENDER: " + m.getSender() + " MESSAGE: " + m.getText());
        	GameState.addInvite(m);
        }
		numOfInvites = inviteMessages.size();
		inviteMessages.clear();
		
       buds = GameState.getBuddies();
        if(buds != null) {
		    for(String name : buds.keySet()) {
		    	Log.d("Friends", name + " " + (buds.get(name)? "online" : "offline"));
		    }
        }
		return buds;
	}
	
	protected void onPostExecute(HashMap<String, Boolean> result) {
		Log.d("LoadBuddies", "begin onPostExecute");
		if (numOfChats > 0) {
			Toast.makeText(mContext, numOfChats + " new messages!", Toast.LENGTH_LONG).show();
		}
		if (numOfInvites > 0) {
			Toast.makeText(mContext, numOfInvites + " new invites!", Toast.LENGTH_LONG).show();
		}
		
		setContentView(R.layout.invite_list_layout);
		myAdapter = new InviteListAdapter(mContext, R.layout.invite_row, inviteList);
		setListAdapter(myAdapter);
		dialog.dismiss();
	}
}	
	
	
	

}
